package com.venus.mq.storage;

import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import lombok.Data;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by qts on 2018/12/10.
 * 用于落盘消息文件
 */
@Data
public class TopicFile {

    protected static final InternalLogger log = InternalLoggerFactory.getInstance("TopicStore");

    //总的topic 落盘文件
    private static final AtomicInteger TOTAL_TOPIC_FILES = new AtomicInteger(0);

    //用于文件的读写
    protected FileChannel fileChannel;

    //用于记录当前文件写的位置
    protected final AtomicInteger wrotePosition = new AtomicInteger(0);

    //日志文件名字
    private String fileName;

    private File file;

    //文件映射
    private MappedByteBuffer mappedByteBuffer;

    protected int fileSize;

    /**
     * 初始化参数
     * @param fileName
     * @param fileSize
     * @throws IOException
     */
    private void init(final String fileName, final int fileSize) throws IOException {

        this.fileName = fileName;
        try {
            this.fileChannel = new RandomAccessFile(this.file, "rw").getChannel();
            this.mappedByteBuffer = this.fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, fileSize);
        } catch (FileNotFoundException e) {
            log.error("create file channel " + this.fileName + " Failed. ", e);
            throw e;
        } catch (IOException e) {
            log.error("map file " + this.fileName + " Failed. ", e);
            throw e;
        } finally {
                this.fileChannel.close();
            }
        }
}
